<?php

namespace common\helpers\files;

use \yii;
use yii\web\UploadedFile;

class File
{
    public $category = '';
    public $timeDir = true;
    private static $instance;

    const UPLOAD_PATH = 'uploads/';
    /**\
     * @var $uploadedFile UploadedFile
     */
    public $uploadedFile;

    public function __construct($uploadedFile = null, $category = null, $timeDir = null)
    {
        if ($uploadedFile) {
            $this->uploadedFile = $uploadedFile;
        }
        if ($category) {
            $this->category = $category;
        }
        if ($timeDir) {
            $this->timeDir = $timeDir;
        }
    }

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new self();
        }
    }

    public function upload($saveName = null)
    {
        $savePath = $this->getSavePath($this->category, $this->timeDir);
        $filename = $this->getFileName($saveName);
        $stream = fopen($this->uploadedFile->tempName, 'r+');
        if (!Yii::$app->awss3Fs->putStream($savePath . $filename, $stream)) {
            throw new yii\web\ServerErrorHttpException('File upload failed.');
        }
        @unlink($this->uploadedFile->tempName);
        return getenv('OSS_FILE_ROOT') . $savePath . $filename;
    }

    public static function delete($uri)
    {
        if (strstr($uri, getenv('OSS_FILE_ROOT'))) {
            $path = str_replace(getenv('OSS_FILE_ROOT'), '', $uri);
            if (Yii::$app->awss3Fs->has($path)) {
                Yii::$app->awss3Fs->delete($path);
            }
        }
        return true;
    }

    public static function getLink($uri)
    {
        if (!is_file(self::getAbsPath($uri))) {
            return 'http://ww1.sinaimg.cn/large/675eb504gy1fe73shx2rnj2019019we9.jpg';
        }
        $url = self::UPLOAD_PATH . $uri;
        return $url;
    }

    public static function getAbsoluteLink($uri)
    {
        if (!is_file(self::getAbsPath($uri))) {
            return 'http://ww1.sinaimg.cn/large/675eb504gy1fe73shx2rnj2019019we9.jpg';
        }
        $url = Yii::$app->request->hostInfo . '/' . self::UPLOAD_PATH . $uri;
        return $url;
    }

    public static function getAbsPath($savePath)
    {
        return \Yii::getAlias('@frontend') . '/web/' . self::UPLOAD_PATH . $savePath;
    }

    public function getSavePath($category = null)
    {
        $path = '';
        if ($category) {
            $path = $path . $category . '/';
        }
        if ($this->timeDir) {
            $path = $path . date('Ymd') . '/';
        }
        return $path;
    }

    public function getFileName($saveName = null)
    {
        return ($saveName ? $saveName : uniqid()) . '.' . $this->uploadedFile->extension;
    }
}
